/**
 * 附件管理组件
 */
import React, { useState, useEffect } from 'react';
import {
  Card,
  Upload,
  Button,
  List,
  Space,
  Tag,
  Popconfirm,
  message,
  Progress,
  Tooltip,
  Typography,
} from 'antd';
import {
  UploadOutlined,
  DeleteOutlined,
  DownloadOutlined,
  FileOutlined,
  PaperClipOutlined,
} from '@ant-design/icons';
import { request } from '@umijs/max';
import type { UploadFile, UploadProps } from 'antd';

const { Text } = Typography;

interface AttachmentItem {
  filename: string;
  original_filename: string;
  url: string;
  size: number;
  content_type: string;
  created_time?: number;
}

interface AttachmentManagerProps {
  value?: AttachmentItem[];
  onChange?: (attachments: AttachmentItem[]) => void;
  maxCount?: number;
  maxSize?: number; // MB
  title?: string;
  disabled?: boolean;
}

const AttachmentManager: React.FC<AttachmentManagerProps> = ({
  value = [],
  onChange,
  maxCount = 10,
  maxSize = 10,
  title = "邮件附件",
  disabled = false,
}) => {
  const [attachments, setAttachments] = useState<AttachmentItem[]>(value);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<{ [key: string]: number }>({});

  // 同步外部值变化
  useEffect(() => {
    setAttachments(value);
  }, [value]);

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取文件图标
  const getFileIcon = (contentType: string) => {
    if (contentType.startsWith('image/')) {
      return '🖼️';
    } else if (contentType.includes('pdf')) {
      return '📄';
    } else if (contentType.includes('word')) {
      return '📝';
    } else if (contentType.includes('excel') || contentType.includes('spreadsheet')) {
      return '📊';
    } else if (contentType.includes('powerpoint') || contentType.includes('presentation')) {
      return '📽️';
    } else if (contentType.includes('zip') || contentType.includes('compressed')) {
      return '🗜️';
    } else {
      return '📎';
    }
  };

  // 获取文件类型标签颜色
  const getFileTypeColor = (contentType: string): string => {
    if (contentType.startsWith('image/')) return 'green';
    if (contentType.includes('pdf')) return 'red';
    if (contentType.includes('word')) return 'blue';
    if (contentType.includes('excel')) return 'orange';
    if (contentType.includes('powerpoint')) return 'purple';
    return 'default';
  };

  // 上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    maxCount: maxCount - attachments.length,
    beforeUpload: (file) => {
      // 检查文件大小
      if (file.size > maxSize * 1024 * 1024) {
        message.error(`文件大小不能超过 ${maxSize}MB`);
        return false;
      }

      // 检查文件数量
      if (attachments.length >= maxCount) {
        message.error(`最多只能上传 ${maxCount} 个附件`);
        return false;
      }

      return true;
    },
    customRequest: async ({ file, onProgress, onSuccess, onError }) => {
      try {
        setUploading(true);
        const formData = new FormData();
        formData.append('file', file as File);

        const response = await request('/api/files/upload/attachment', {
          method: 'POST',
          data: formData,
          onUploadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              setUploadProgress(prev => ({
                ...prev,
                [(file as File).name]: percent
              }));
              onProgress?.({ percent });
            }
          },
        });

        if (response.success) {
          const newAttachment: AttachmentItem = response.data;
          const newAttachments = [...attachments, newAttachment];
          setAttachments(newAttachments);
          onChange?.(newAttachments);
          
          // 清除进度
          setUploadProgress(prev => {
            const newProgress = { ...prev };
            delete newProgress[(file as File).name];
            return newProgress;
          });
          
          onSuccess?.(response.data);
          message.success(`${(file as File).name} 上传成功`);
        } else {
          onError?.(new Error(response.message || '上传失败'));
          message.error(response.message || '上传失败');
        }
      } catch (error: any) {
        onError?.(error);
        message.error(error.message || '上传失败');
      } finally {
        setUploading(false);
      }
    },
    showUploadList: false,
    disabled: disabled || attachments.length >= maxCount,
  };

  // 删除附件
  const handleDelete = async (attachment: AttachmentItem) => {
    try {
      // 从列表中移除
      const newAttachments = attachments.filter(item => item.filename !== attachment.filename);
      setAttachments(newAttachments);
      onChange?.(newAttachments);
      
      // 可选：调用后端删除文件
      // await request(`/api/files/delete/attachments/${attachment.filename}`, {
      //   method: 'DELETE',
      // });
      
      message.success('附件删除成功');
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  // 下载附件
  const handleDownload = (attachment: AttachmentItem) => {
    const link = document.createElement('a');
    link.href = attachment.url;
    link.download = attachment.original_filename;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <Card 
      title={
        <Space>
          <PaperClipOutlined />
          {title}
          <Tag color="blue">{attachments.length}/{maxCount}</Tag>
        </Space>
      } 
      size="small"
      extra={
        <Upload {...uploadProps}>
          <Button 
            icon={<UploadOutlined />} 
            loading={uploading}
            disabled={disabled || attachments.length >= maxCount}
            size="small"
          >
            添加附件
          </Button>
        </Upload>
      }
    >
      {attachments.length === 0 ? (
        <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
          <FileOutlined style={{ fontSize: '24px', marginBottom: '8px' }} />
          <div>暂无附件</div>
          <div style={{ fontSize: '12px' }}>
            支持 PDF、Word、Excel、PPT、图片、压缩包等格式
          </div>
        </div>
      ) : (
        <List
          size="small"
          dataSource={attachments}
          renderItem={(attachment) => (
            <List.Item
              actions={[
                <Tooltip title="下载">
                  <Button
                    type="text"
                    size="small"
                    icon={<DownloadOutlined />}
                    onClick={() => handleDownload(attachment)}
                  />
                </Tooltip>,
                <Popconfirm
                  title="确定要删除这个附件吗？"
                  onConfirm={() => handleDelete(attachment)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Tooltip title="删除">
                    <Button
                      type="text"
                      size="small"
                      icon={<DeleteOutlined />}
                      danger
                      disabled={disabled}
                    />
                  </Tooltip>
                </Popconfirm>,
              ]}
            >
              <List.Item.Meta
                avatar={
                  <span style={{ fontSize: '20px' }}>
                    {getFileIcon(attachment.content_type)}
                  </span>
                }
                title={
                  <Space>
                    <Text ellipsis style={{ maxWidth: '200px' }}>
                      {attachment.original_filename}
                    </Text>
                    <Tag 
                      size="small" 
                      color={getFileTypeColor(attachment.content_type)}
                    >
                      {attachment.content_type.split('/')[1]?.toUpperCase() || 'FILE'}
                    </Tag>
                  </Space>
                }
                description={
                  <Space>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {formatFileSize(attachment.size)}
                    </Text>
                    {uploadProgress[attachment.original_filename] !== undefined && (
                      <Progress
                        percent={uploadProgress[attachment.original_filename]}
                        size="small"
                        style={{ width: '100px' }}
                      />
                    )}
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      )}
      
      {attachments.length > 0 && (
        <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
          总大小: {formatFileSize(attachments.reduce((total, item) => total + item.size, 0))}
          {maxSize && ` / ${maxSize}MB`}
        </div>
      )}
    </Card>
  );
};

export default AttachmentManager;
